package life.majiang.community.provider;/**
 * @author ae
 * @date 2021-10-19 19:58
 */

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import life.majiang.community.dto.AccessTokenDTO;
import life.majiang.community.dto.GiteeUser;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description: TODO
 * @author ae
 * @data 2021/10/19 19:58
 * @version 1.0
 */
@Component
public class GiteeProvider {

    public String getAccessToken(AccessTokenDTO accessTokenDTO){
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();

        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                    .url("https://gitee.com/oauth/token")
                    .post(body)
                    .build();
        try (Response response = client.newCall(request).execute()) {
            String string = response.body().string();
            JSONObject jsonObject = JSONObject.parseObject(string);
            String accessToken = (String) jsonObject.get("access_token");
            return accessToken; // 得到的access token
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public GiteeUser getUser(String accessToken){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://gitee.com/api/v5/user?access_token="+accessToken)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String string = response.body().string();
            GiteeUser githubUser = JSON.parseObject(string, GiteeUser.class); // 根据json和该domain的已有属性，调用其set
            return githubUser;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
